package org.icnmasjid.member.webapp.action;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.icnmasjid.member.model.Person;
import org.icnmasjid.member.model.Role;
import org.icnmasjid.member.model.SubOrg;
import org.icnmasjid.member.service.LookupManager;
import org.icnmasjid.member.service.PersonManager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

public class SyncMailingLists extends BaseFormController {

	private PersonManager personManager;
	private LookupManager lookupManager;

    public SyncMailingLists() {
    	setCommandClass(Person.class);
    	setCommandName("person");
	}

    @Override
    protected boolean isFormSubmission(HttpServletRequest request) {
    	return true;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }        
        Role role = lookupManager.getRoleByName("Student-2010");
        // get the list of grades
        List<SubOrg> list = lookupManager.getObjects(SubOrg.class);
        List<String> masterList = new ArrayList<String>();
        for ( SubOrg so: list ) {
        	List<Person> persons = personManager.getParents(so, role);
        	System.out.println(so.getName());
        	System.out.println(so.getMailingList());
        	System.out.println(persons.size());
        	// for each mailing list create an list of numbers
        	// dump them into a file
        	// then call the sync command line mailman command
        	// its that simple
        	// sync mailing list
        	if ( StringUtils.isNotBlank(so.getMailingList()) ) {
        		List<String> emailList = new ArrayList<String>();
        		for (Person p: persons) {
        			if ( StringUtils.isNotBlank(p.getEmail() )) {
        				emailList.add(p.getEmail());
        			}
        			
        			if ( StringUtils.isNotBlank(p.getEmail2() )) {
        				emailList.add(p.getEmail2());
        			}
        			
        			if ( p.getSpouse() != null ) {
            			if ( StringUtils.isNotBlank(p.getSpouse().getEmail() )) {
            				emailList.add(p.getSpouse().getEmail());
            			}
            			
            			if ( StringUtils.isNotBlank(p.getSpouse().getEmail2() )) {
            				emailList.add(p.getSpouse().getEmail2());
            			}        				
        			}        			
        		} // end for
    			// now dump the list to a flat file
    			// call sync program for the mailing list and file
    			try {
    				FileOutputStream erasor = new FileOutputStream("/tmp/" + so.getMailingList());
    				erasor.write((new String()).getBytes());
    				erasor.close();    				
    			} catch (Throwable t) {
    				t.printStackTrace();
    			}
        		
    			BufferedWriter bf = new BufferedWriter(new FileWriter("/tmp/" + so.getMailingList()));
    			for ( String email : emailList) {
    				bf.write(email);
    				bf.newLine();
    			}
    			bf.close();
    			
    			/*
    			// now call the sync program
    			try {
    				Runtime.getRuntime().exec(
    						"echo \"yes\" | scp -v /tmp/" + so.getMailingList() + " icnyouth@icnyouth.org:/tmp");    				
    				Runtime.getRuntime().exec(
    						"echo \"yes\" | ssh -v icnyouth@icnyouth.org /usr/lib/mailman/bin/sync_members -w=no -g=no -d=no -a=no -f /tmp/" 
    							+ so.getMailingList() + " " + so.getMailingList());
    			} catch (Throwable t) {
    				t.printStackTrace();
    			}
    			*/
        		masterList.addAll(emailList);
        	}
        }
        
		try {
			FileOutputStream erasor = new FileOutputStream("/tmp/Parents2010");
			erasor.write((new String()).getBytes());
			erasor.close();    				
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
		BufferedWriter bf = new BufferedWriter(new FileWriter("/tmp/Parents2010"));
		for ( String email : masterList) {
			bf.write(email);
			bf.newLine();
		}
		bf.close();
		
		//dont do this if sync is false
		Boolean dontSync = Boolean.parseBoolean(request.getParameter("dontSync"));
		if ( !dontSync ) {
			// now call the sync program
			try {
				String s = null;
				Process p = Runtime.getRuntime().exec("/usr/share/tomcat6/scripts/sync.sh");
				
				BufferedReader stdInput = new BufferedReader(new 
				     InputStreamReader(p.getInputStream()));
				
				BufferedReader stdError = new BufferedReader(new 
				     InputStreamReader(p.getErrorStream()));
				
				// read the output from the command
				System.out.println("Here is the standard output of the command:\n");
				while ((s = stdInput.readLine()) != null) {
				    System.out.println(s);
				}
				
				// read any errors from the attempted command
				System.out.println("Here is the standard error of the command (if any):\n");
				while ((s = stdError.readLine()) != null) {
				    System.out.println(s);
				}
				
				/*
				Runtime.getRuntime().exec(
				"echo \"yes\" | scp -v /tmp/Parents2010 icnyouth@icnyouth.org:/tmp/Parents2010");			
				Runtime.getRuntime().exec(
						"echo \"yes\" | ssh -v icnyouth@icnyouth.org /usr/lib/mailman/bin/sync_members -w=no -g=no -d=no -a=no -f /tmp/Parents2010 Parents2010");
				*/
			} catch (Throwable t) {
				t.printStackTrace();
			}
		}
        
        
        return new ModelAndView("importReport");
    }

	public LookupManager getLookupManager() {
		return lookupManager;
	}

	public void setLookupManager(LookupManager lookupManager) {
		this.lookupManager = lookupManager;
	}

	public PersonManager getPersonManager() {
		return personManager;
	}
	
    public void setPersonManager(PersonManager personManager) {
        this.personManager = personManager;
    }
	

}
